﻿using System;
using System.Collections.ObjectModel;

namespace SilverMindMap.Core.Model
{
    public class MindMap : ObservableObject
    {        
        private readonly ObservableCollection<Node> _nodes;
        private readonly ReadOnlyObservableCollection<Node> _nodesView;
        private Node _rootNode;

        public MindMap()
        {
            _nodes = new ObservableCollection<Node>();
            _nodesView = new ReadOnlyObservableCollection<Node>(_nodes);
            _rootNode = null;
        }

        public Node RootNode
        {
            get { return _rootNode; }
            set
            {
                if (_rootNode == value)
                    return;

                if (value != null && !_nodes.Contains(value))
                    throw new ArgumentException("Root node must be null or must belong to this MindMap");

                _rootNode = value;
                RaisePropertyChanged("RootNode");
            }
        }

        public ReadOnlyObservableCollection<Node> Nodes
        {
            get { return _nodesView; }
        }

        public void AddNode(Node node)
        {
            if (_nodes.Contains(node))
                return;

            if (node.MindMap != null)
                node.MindMap.RemoveNode(node);

            _nodes.Add(node);
            node.MindMap = this;            
        }

        public bool RemoveNode(Node node)
        {
            if (!_nodes.Contains(node))
                return false;

            _nodes.Remove(node);
            node.MindMap = null;

            if (this.RootNode == node)
                this.RootNode = null;

            return true;
        }
    }
}
